package ws

import (
    "github.com/kataras/iris/v12"
    "github.com/kataras/iris/v12/websocket"
    "github.com/kataras/neffos"
    "log"
)

type IrisWebSocket struct {
    ws *neffos.Server
}

// NewWebSocket 初始化 WebSocket
func NewWebSocket(app *iris.Application) *IrisWebSocket {

    i := &IrisWebSocket{}

    // 使用gobwas/ws模块实现WebSocket
    i.ws = websocket.New(websocket.DefaultGobwasUpgrader, websocket.Events{
        // 将回调函数暴露给使用者
        websocket.OnNativeMessage: i.ReceiveMessage,
    })

    // 监听服务是否链接
    i.ws.OnConnect = func(c *websocket.Conn) error {
        log.Printf("[%s] 服务已连接!", c.ID())
        return nil
    }

    // 监听链接是否断开
    i.ws.OnDisconnect = func(c *websocket.Conn) {
        log.Printf("[%s] 链接已断开!", c.ID())
    }

    // 设置WebSocket链接地址
    app.Any("/websocket", websocket.Handler(i.ws))

    return i
}

// SendMessage 发送消息
func (i *IrisWebSocket) SendMessage(message string) {

    i.ws.Broadcast(nil, websocket.Message{
        Body:     []byte(message), // 消息体
        IsNative: true,            // 使用自己的格式传递数据
    })
}

// ReceiveMessage 接收客户消息
func (i *IrisWebSocket) ReceiveMessage(nsConn *websocket.NSConn, msg websocket.Message) error {
    log.Printf("接收到客户端消息: %s from [%s]", msg.Body, nsConn.Conn.ID())
    return nil
}
